#!/usr/bin/env python3
"""
Script to fix section hierarchy in LaTeX files:
- Replace \section*{3.X Title} with \section{Title}
- Replace \section*{3.X.Y Title} with \subsection{Title}
- Replace \section*{Title} (no number) with \subsubsection{Title}
"""

import re
import glob

def fix_section_hierarchy(file_path):
    """Fix section hierarchy in a single file."""

    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    original_content = content

    # Pattern 1: \section*{3.X.Y.Z Title} -> \subsubsection{Title} (if any exist)
    content = re.sub(
        r'\\section\*\{3\.\d+\.\d+\.\d+\s+([^}]+)\}',
        r'\\subsubsection{\1}',
        content
    )

    # Pattern 2: \section*{3.X.Y Title} -> \subsection{Title}
    content = re.sub(
        r'\\section\*\{3\.\d+\.\d+\s+([^}]+)\}',
        r'\\subsection{\1}',
        content
    )

    # Pattern 3: \section*{3.X Title} -> \section{Title}
    content = re.sub(
        r'\\section\*\{3\.\d+\s+([^}]+)\}',
        r'\\section{\1}',
        content
    )

    # Pattern 4: \section*{Title} (no number, not chapter title) -> \subsubsection{Title}
    # Skip the chapter title "第三章 随机模拟" and "习题三"
    lines = content.split('\n')
    for i, line in enumerate(lines):
        # Match \section*{...} that doesn't start with a number or "第" or "习题"
        match = re.match(r'\\section\*\{([^}]+)\}', line)
        if match:
            title = match.group(1)
            # If title doesn't start with number or chapter markers
            if not re.match(r'^\d', title) and not title.startswith('第') and not title.startswith('习题'):
                lines[i] = f'\\subsubsection{{{title}}}'

    content = '\n'.join(lines)

    # Only write if content changed
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return True
    return False

def main():
    """Process all section files."""

    # Process section files
    section_files = sorted(glob.glob('section_*.tex'))

    print(f"Processing {len(section_files)} files...")

    for file_path in section_files:
        changed = fix_section_hierarchy(file_path)
        if changed:
            print(f"✓ Fixed {file_path}")
        else:
            print(f"- No changes needed for {file_path}")

    print("\nDone!")

if __name__ == "__main__":
    main()
